<?php

namespace app\controllers;

use Yii;
use app\models\Base;
use app\models\User;
use app\models\Repair;
use app\models\FormType;
use app\models\FormTag;
use app\models\FormInfo;
use app\models\Setting;
use app\models\CompanyWt;
use app\tools\Re;
use app\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use app\tools\JPushHelper;

class FormController extends BaseController
{
	public function behaviors() {
      $optional =  [
				'company-tag-list-for-select',
				'company-type-list',
				'company-type-info',
				'company-sg-list',
				'get-company-wt'
			];
      return ArrayHelper::merge(parent::behaviors(), [
        'authenticator' => [
          'class' => HttpBearerAuth::class,
          'optional' =>$optional
        ]
      ]);
  }

	//提交表单
	public function actionAddForm() {
		$form_type = Yii::$app->request->post('form_code', '');
		$name = Yii::$app->request->post('name', '');
		$phone = Yii::$app->request->post('phone', '');
		$company_name = Yii::$app->request->post('company_name', '');
		$service_type = Yii::$app->request->post('service_type', '');
		$voltage_level = Yii::$app->request->post('voltage_level', 0);
		$capacity = Yii::$app->request->post('capacity', '');
		$operation_type = Yii::$app->request->post('operation_type', 1);
		$company_sg = Yii::$app->request->post('company_sg', 0);
		$company_sg_name = Yii::$app->request->post('company_sg_name', '');
		$area_info = Yii::$app->request->post('area_info', '');
		$address = Yii::$app->request->post('address', '');
		$install_at = Yii::$app->request->post('install_at', 0);
		$content = Yii::$app->request->post('content', '');
    $company_wt_name = Yii::$app->request->post('company_wt_name', '');
    $province = Yii::$app->request->post('province', '');
    $city = Yii::$app->request->post('city', '');
    $area = Yii::$app->request->post('area', '');
    $address = Yii::$app->request->post('address', '');
    $address_detail = Yii::$app->request->post('address_detail', '');
    $longitude = Yii::$app->request->post('longitude', '');
    $latitude = Yii::$app->request->post('latitude', '');
    $form_desc = Yii::$app->request->post('form_desc', '');
    $form_img = Yii::$app->request->post('form_img', '');
    $specs_type = Yii::$app->request->post('specs_type', '');
    $content_json = Yii::$app->request->post('content_json', ''); //[{"name":"标识牌","specs":"规格11","price":100,"num":10},{"name":"绝缘手套","specs":"规格22","price":200,"num":5}]
    $total_money = Yii::$app->request->post('total_money', '');
    $content_json = empty($content_json) ? '' : $content_json;
    $total_money = empty($total_money) ? '' : $total_money;
		if (empty($form_type) || empty($name) || empty($phone)) {
			return Re::data(null, '参数错误', Re::ERROR);
		}
		if ($form_type == 'dlsg' && !$company_sg && empty($company_sg_name)) {
			return Re::data(null, '请选择或填写施工单位', Re::ERROR);
		}
		$company_wt_id = 0;
		if ($company_wt_name) {
			$companyWt = CompanyWt::find()->where(['name' => $company_wt_name, 'status' => [0,1]])->one();
			if (!$companyWt) {
				$companyWt = new CompanyWt();
				$companyWt->name = $company_wt_name;
				$companyWt->status = 1;
				$companyWt->created_at = time();
				$companyWt->save();
			}
			$company_wt_id = $companyWt->id;
		}
		$formInfo = new FormInfo();
		$formInfo->user_id = Yii::$app->user->id;
		$formInfo->name = $name;
		$formInfo->phone = $phone;
		$formInfo->company_name = $company_name;
		$formInfo->service_type = $service_type;
		$formInfo->voltage_level = $voltage_level;
		$formInfo->capacity = $capacity;
		$formInfo->operation_type = $operation_type;
		$formInfo->company_sg = $company_sg;
		$formInfo->company_sg_name = $company_sg_name;
		$formInfo->company_wt = $company_wt_id;
		$formInfo->content = $content;
		$formInfo->form_type = $form_type;
		$formInfo->area_info = $area_info;
		$formInfo->address = $address;
		$formInfo->install_at = $install_at;
    $formInfo->created_at = time();
    $formInfo->province = $province;
    $formInfo->city = $city;
    $formInfo->area = $area;
    $formInfo->address = $address;
    $formInfo->address_detail = $address_detail;
    $formInfo->lng = $longitude;
    $formInfo->lat = $latitude;
    $formInfo->form_desc = $form_desc;
    $formInfo->form_img = $form_img;
    $formInfo->specs_type = $specs_type;
    $formInfo->content_json = $content_json;
    $formInfo->total_money = $total_money;
		if (!$formInfo->save()) {
			return Re::data(null, '表单信息保存失败', Re::ERROR);
		}
		$setting = Setting::findOne(1);
    if ($setting->open_push_admin) {
    	$formType = FormType::find()->where(['code' => $form_type])->one();
    	$user_admin_id_arr = User::find()->where(['status' => 1, 'is_admin' => 1])->andWhere("FIND_IN_SET('$form_type', form_type_ids)")->select("id")->column();
			if ($user_admin_id_arr) {
				$extra = [
		      	'push_type' => 'bdtz',
		      	'push_user_type' => 3
		  	];
				JPushHelper::pushNotifyByReg($user_admin_id_arr, $formType->name.'订单通知', '有新的'.$formType->name.'订单，请至后台查看', $extra);
			}
    }
		return Re::data(['data' => $formInfo->id]);
	}

	public function actionCompanySgList(){
			$service_type = Yii::$app->request->post('service_type', '');
			$voltage_level = Yii::$app->request->post('voltage_level', 0);
			$companyQuery = Repair::find()->where(['type' => [2,3], 'status' => 1]);
			if ($voltage_level) {
				$companyQuery->andWhere(['voltage_level' => $voltage_level]);
			}
			if ($service_type) {
				$service_type_arr = explode(',', $service_type);
				$condition = '';
				foreach ($service_type_arr as $v) {
					$condition .= "FIND_IN_SET('$v', service_type) and ";
				}
				$condition = rtrim($condition, ' and ');
				$companyQuery->andWhere($condition);
			}
			$companyList = $companyQuery->select('id, name')->all();
			$companyData = [];
			if ($companyList) {
				foreach ($companyList as $v) {
					$companyData[] = [
						'id' => $v->id,
						'name' => $v->name,
						'target_url' => Yii::$app->params['domain_wap'].'/#/?type=1&id='.$v->id
					];
				}
			}
			$company_wp = [
				'id' => -1,
				'name' => '委托安排',
				'target_url' => ''
			];
			$company_sd = [
				'id' => 0,
				'name' => '其他单位',
				'target_url' => ''
			];
			array_push($companyData, $company_wp, $company_sd);
			return Re::data(['data' => $companyData]);
	}

	public function actionFormTagListForSelect(){
			$type = Yii::$app->request->post('type', 1);
			$tagList = FormTag::find()->where(['type' => $type, 'status' => 1])->select('id, name')->all();
			return Re::data(['data' => $tagList]);
	}

	public function actionFormTypeList(){
			$typeList = FormType::find()->where(['status' => 1])->select('code, name')->orderBy('level asc')->all();
			return Re::data(['data' => $typeList]);
	}

	public function actionFormTypeInfo(){
			$code = Yii::$app->request->post('code', '');
			$typeInfo = FormType::find()->where(['code' => $code])->one();
			if (!$typeInfo) {
				return Re::data(null, '表单类型信息读取失败', Re::ERROR);
			}
			$data = [
				'id' => $typeInfo->id,
				'name' => $typeInfo->name,
				'code' => $typeInfo->code,
				'content' => $typeInfo->content,
				//'content' => '',
				'desc' => $typeInfo->desc,
				//'desc' => '',
				'target_url' => Yii::$app->params['domain_wap'].'/#/?type=3&id='.$typeInfo->id
			];
			return Re::data(['data' => $data]);
	}

	public function actionMyFormList(){
		$page = Yii::$app->request->post('page', 0);
		$form_list = FormInfo::find()->where(['user_id' => Yii::$app->user->id, 'status' => 1])->orderBy("created_at desc")->limit(10)->offset(10*$page)->all();
		$form_data = [];
		if ($form_list) {
			foreach ($form_list as $v) {
					$form_data[] = [
							'id' => $v->id,
							'name' => $v->type->parent->name.'.'.$v->type->name,
							'is_read' => $v->is_read,
					];
			}
		}
		return Re::data(['data' => $form_data]);
	}

	public function actionWyjzList(){
		$page = Yii::$app->request->post('page', 0);
		$form_list = FormInfo::find()->where(['user_id' => Yii::$app->user->id, 'form_type' => 'wyjz', 'status' => 1])->orderBy("created_at desc")->limit(10)->offset(10*$page)->all();
		$form_data = [];
		if ($form_list) {
			foreach ($form_list as $v) {
					$form_data[] = [
							'id' => $v->id,
							'address' => $v->address,
							'is_read' => $v->is_read,
					];
			}
		}
		return Re::data(['data' => $form_data]);
	}

	public function actionFormListForAdmin(){
		$page = Yii::$app->request->post('page', 0);
		$form_type = Yii::$app->request->post('form_type', '');
		$form_query = FormInfo::find()->where(['status' => 1]);
		if ($form_type) {
			$form_type_info = FormType::find()->where(['code' => $form_type])->one();
			if (!$form_type_info) {
				return Re::data(null, '表单类型信息读取失败', Re::ERROR);
			}
			if ($form_type_info->level == 2) {
				$form_query->andWhere(['form_type' => $form_type]);
			} else {
				$form_type_code_arr = FormType::find()->where(['parent_id' => $form_type_info->id])->select('code')->column();
				if ($form_type_code_arr) {
					$form_query->andWhere(['form_type' => $form_type_code_arr]);
				}
			}
		}
		$form_list = $form_query->orderBy("created_at desc")->limit(10)->offset(10*$page)->all();
		$form_data = [];
		if ($form_list) {
			foreach ($form_list as $v) {
					$form_data[] = [
							'id' => $v->id,
							'name' => $v->type->parent->name.'.'.$v->type->name,
							'user_name' => $v->user->name,
							'user_phone' => $v->user->phone,
							'is_read' => $v->is_read,
					];
			}
		}
		return Re::data(['data' => $form_data]);
	}

	public function actionFormInfo(){
		$id = Yii::$app->request->post('id', 0);
		$form_info = FormInfo::findOne($id);
		if (empty($form_info)) {
			return Re::data(null, '表单信息读取失败', Re::ERROR);
		}
		$service_type_name = '';
		if ($form_info->service_type) {
			$service_type_arr = explode(',', $form_info->service_type);
			foreach ($service_type_arr as $v) {
				$form_tag = FormTag::findOne($v);
				$service_type_name .= $form_tag->name . ',';
			}
			rtrim($service_type_name, ',');
		}
		$company_sg_name = '';
		if ($form_info->company_sg == 0) {
			$company_sg_name = $form_info->company_sg_name;
		}
		if ($form_info->company_sg > 0) {
			$company_sg_name = $form_info->company->name;
		}
		$form_data = [
			'user_name' => $form_info->user->name,
			'user_phone' => $form_info->user->phone,
			'company_name' => $form_info->company_name,
			'service_type' => $service_type_name,
      'voltage_level' => $form_info->voltage_level ? $form_info->voltage->name : '',
      'capacity' => $form_info->capacity,
      'form_type' => $form_info->form_type,
      'operation_type' => $form_info->operation_type,
			'company_sg_name' => $company_sg_name,
			'company_wt_name' => $form_info->company_wt ? $form_info->companyWt->name : '',
			'area_info' => $form_info->area_info,
			'address' => $form_info->address,
			'install_time' => $form_info->install_at ? date('Y.m.d', $form_info->install_at) : '',
			'content' => $form_info->content,
			'is_read' => $form_info->is_read,
      'result' => $form_info->result,
      'address_detail' => $form_info->address_detail,
      'longitude' => $form_info->lng,
      'latitude' => $form_info->lat,
      'province' => $form_info->province,
      'city' => $form_info->city,
      'city' => $form_info->city,
      'form_desc' => $form_info->form_desc,
      'form_img' => $form_info->form_img,
      'specs_type' => $form_info->specs_type,
      'content_json' => $form_info->content_json ? json_decode($form_info->content_json) : [],
      'total_money' => $form_info->total_money,
		];
		return Re::data(['data' => $form_data]);
	}

	public function actionReadForm(){
			$id = Yii::$app->request->post('id', 0);
			$content = Yii::$app->request->post('content', '');
			if (empty($id) || empty($content)) {
				return Re::data(null, '参数错误', Re::ERROR);
			}
			$form_info = FormInfo::findOne($id);
			if (!$form_info) {
					return Re::data(null, '表单信息读取失败', Re::ERROR);
			}
			$form_info->result = $content;
			$form_info->is_read = 1;
			$form_info->save();
			return Re::data();
	}

	public function actionGetCompanyWt(){
			$name = Yii::$app->request->post('name', '');
			if (empty($name)) {
				return Re::data(['data' => []]);
			}
			$company_list = CompanyWt::find()->where(['status' => 1])->andWhere(['like', 'name', $name])->select("id, name")->all();
			return Re::data(['data' => $company_list]);
	}
}
